import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from './router'

// 解决路由冗余报错
const originaPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originaPush.call(this, location).catch((err) => err)
}

Vue.use(VueRouter)

const router = new VueRouter({
  routes,
  scrollBehavior(to, from, savedPosition) {
    return { y: 0 }
  }
})

import store from '@/store'

// 全局前置导航守卫
router.beforeEach(async function (to, from, next) {
  const token = localStorage.getItem('token')
  // 登陆状态
  if (token) {
    if (to.path === '/login' || to.path === '/register') return next('/')
    let userName = store.state.user.userInfo.name
    // 登录了 且有用户信息
    if (userName) {
      next()
      // 登录了 没有用户信息
    } else {
      // 获取用户信息
      try {
        await store.dispatch('getUserInfo')
        next()
        // token 失效清空token 重新登录
      } catch (error) {
        await store.dispatch('userLogOut')
        next('/login')
      }
    }
    // 未登录状态
  } else {
    next()
    if (
      to.path == '/center/myorder' ||
      to.path == '/center/grouporder' ||
      to.path == '/shopCart' ||
      to.path == '/pay' ||
      to.path == '/paysuccess'
    )
      return next('/login')
  }
})

export default router
